using System;
using Locomotion;
using UnityEngine;
using Random = UnityEngine.Random;
using PrimeTween;

namespace Controls
{
    public class AiCharacterController : MonoBehaviour
    {
        [SerializeField] private JumpCharacter character;
        [SerializeField] private float maxRangeFactor = 0.1f;
        [SerializeField] private float boundX = 3f;


        private void OnEnable()
        {
            GroundDetector.AnyCharacterGroundedChanged += GroundDetectorOnAnyCharacterGroundedChanged;
        }
        
        private void OnDisable()
        {
            GroundDetector.AnyCharacterGroundedChanged -= GroundDetectorOnAnyCharacterGroundedChanged;
        }

        private void RefreshJumpParam()
        {
            float rangeXLeft = -maxRangeFactor * Mathf.Abs(character.transform.position.x + boundX);
            float rangeXRight = maxRangeFactor * Mathf.Abs(character.transform.position.x - boundX);
            Vector2 jumpDirection = new(
                Random.Range(rangeXLeft, rangeXRight),
                1f);
            character.PrepareJump(jumpDirection);
        }

        private void GroundDetectorOnAnyCharacterGroundedChanged(GroundDetector.GroundChangedEventArgs groundChangedEventArgs)
        {
            if (!groundChangedEventArgs.GroundDetector.IsGrounded)
            {
                return;
            }
            
            RefreshJumpParam();
        }

        private void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.red;
            Gizmos.DrawLine(
                character.transform.position, 
                character.transform.position + new Vector3(-maxRangeFactor * boundX, 1f));
            Gizmos.DrawLine(
                character.transform.position, 
                character.transform.position + new Vector3(maxRangeFactor * boundX, 1f));
        }
    }
}
